package com.basic.library.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;

import androidx.annotation.Nullable;

import com.basic.library.R;

/**
 * @author yj
 * @description
 */
public class ArrowTextView extends androidx.appcompat.widget.AppCompatTextView {
    private int arrowBgColor = Color.WHITE;
    private int arrowTextRadius = 2;

    public ArrowTextView(Context context) {
        this(context, null);
    }

    public ArrowTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, android.R.attr.textViewStyle);
    }

    public ArrowTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setPadding(getPaddingLeft(), getPaddingTop() + arrowHeight, getPaddingRight(), getPaddingBottom());
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ArrowTextView);
            arrowBgColor = typedArray.getColor(R.styleable.ArrowTextView_arrowBgColor, arrowBgColor);
            arrowTextRadius = typedArray.getDimensionPixelSize(R.styleable.ArrowTextView_arrowTextRadius, arrowTextRadius);
        }
    }

    int arrowHeight = 12;
    int s = arrowHeight / 4 * 3;

    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);   //设置画笔抗锯齿
        paint.setStrokeWidth(2);    //设置线宽
        paint.setColor(arrowBgColor);  //设置线的颜色

        int height = getHeight();   //获取View的高度
        int width = getWidth();     //获取View的宽度

        //框定文本显示的区域
//        canvas.drawRoundRect(new RectF(getPaddingLeft(), getPaddingTop() - arrowHeight, width - getPaddingRight(), height - getPaddingBottom()), 6, 6, paint);
        canvas.drawRoundRect(new RectF(0, arrowHeight, width, height), arrowTextRadius, arrowTextRadius, paint);

        Path path = new Path();

        //以下是绘制文本的那个箭头
        path.moveTo(width / 2 - s, arrowHeight);// 三角形顶点
        path.lineTo(width / 2, 0);   //三角形左边的点
        path.lineTo(width / 2 + s, arrowHeight);   //三角形右边的点

        path.close();
        canvas.drawPath(path, paint);
        super.onDraw(canvas);
    }
}
